
#pragma once

#include <memory>
#include <string>
#include <vector>
#include <map>
#include <boost/thread.hpp>
#include <nlohmann/json.hpp>
#include <functional>
#include <chrono>

#include "CUploadBatch.h"

// Forward declarations
class CTableManager;
class CTableBase;


using json = nlohmann::json;

// Upload callback function type
typedef std::function<void(const std::string& jsonData)> UploadCallback;


class CUpLoadServer
{
public:
	CUpLoadServer();
	virtual ~CUpLoadServer();

	// Set the table manager
	virtual void setTableManager(CTableManager* tableManager);
	
	// Start the upload server
	virtual int start();
	
	// Stop the upload server
	virtual int stop();
	
	// Set retry configuration
	virtual void setRetryConfig(int maxRetryCount = 3, int retryIntervalSeconds = 5, int maxErrorCount = 10);
	

	virtual void setUploadCallback(const UploadCallback& uploadCallback);
	
	
	// Handle upload result from external async upload class
	virtual void onUploadResult(const std::string& batchId);

private:
	// Main upload loop
	virtual void uploadLoop();
	
	

	virtual std::string serializeUploadBatch(const CUpLoadBatchPtr& uploadBatch);
	virtual int handleUploadSuccess(const CUpLoadBatchPtr& uploadBatch);
	virtual int handleUploadFailed(const CUpLoadBatchPtr& uploadBatch);
	virtual int handleUpload(const CUpLoadBatchPtr& uploadBatch);

	CUpLoadBatchPtr getUpLoadBatch();

private:
	CTableManager* m_tableManager;
	
	// Current upload batch
	CUpLoadBatchPtr m_currentUploadBatch;
	
	
	// Retry configuration
	int m_maxRetryCount;
	int m_retryIntervalSeconds;
	int m_timeOutIntervalSeconds;
	// Thread control
	boost::thread m_uploadThread;
	bool m_running;

	// Callbacks
	UploadCallback m_uploadCallback;
};

typedef std::shared_ptr<CUpLoadServer> CUpLoadServerPtr;

